package cn.stylefeng.guns.modular.fsjs.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.util.ExcellUtil;
import cn.stylefeng.guns.core.util.ServerResponse;
import cn.stylefeng.guns.modular.system.model.Basemsg;
import cn.stylefeng.guns.modular.system.model.Indenteruwy;
import cn.stylefeng.guns.modular.system.model.Midwater;
import cn.stylefeng.guns.modular.system.model.Swyreport;
import cn.stylefeng.guns.modular.system.model.User;
import cn.stylefeng.guns.modular.system.service.IUserService;
import cn.stylefeng.guns.modular.system.dao.SwyreportMapper;
import cn.stylefeng.guns.modular.fsjs.service.ISwyreportService;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2019-03-06
 */
@Service
public class SwyreportServiceImpl extends ServiceImpl<SwyreportMapper, Swyreport> implements ISwyreportService {
	String mainPath="";
	@Autowired
	private SwyreportMapper swyreportMapper;
	@Autowired
    private IUserService userService;
	@Override
	@Transactional(propagation =Propagation.REQUIRED,rollbackFor=Exception.class,isolation = Isolation.READ_COMMITTED)
	public Object pushMsg(HttpServletRequest request, List<Swyreport> swyreportLi) {
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		User user = userService.selectById(ShiroKit.getUser().getId());
    	if(swyreportMapper.getIfComit(user)>0){
			return ServerResponse.createByErrorMessage("年报数据已经提交，无法修改");
		}
    	mainPath=request.getSession().getServletContext().getRealPath("/")+"\\static\\excell\\";
    	int point=0;
    	for(int i=0;i<swyreportLi.size();i++){
			Swyreport temp=swyreportLi.get(i);
			if(this.checkInput(temp, i)==false){
				return ServerResponse.createByErrorMessage("提交数据有误");
			}
		}
		for(int i=0;i<swyreportLi.size();i++){
			Swyreport temp=swyreportLi.get(i);
			if(this.checkInput(temp, i)==true){
				temp.setAccount(user.getAccount());
				temp.setOperater(user.getAccount());
				temp.setVersion("2");
				temp.setTs(sf.format(new Date()));
				temp.setPrjType((i+0)+"");
			}else{
				continue;
			}
			if(i==0){
				swyreportMapper.delTempMsg(temp);
			}
			
			if(swyreportMapper.pushMsg(temp)==0){
				return ServerResponse.createByErrorMessage("保存数据库出错");
			}else if(i==0){
				point++;
			}
			
		}
//			this.delMsg(user);
			if(point>0){
				//初始化excell成功
				Swyreport temp=swyreportLi.get(0);
				temp.setAccount(user.getAccount());
				ServerResponse cf=(ServerResponse)this.createFile(temp);
				if(cf.getCode()==200){
					//
					List<Swyreport> bsg=this.getMsgByAccountExcell(temp);
					if(bsg.size()>0){
						
						ServerResponse sm=(ServerResponse)this.stuffMsg(bsg,user);
						if(sm.getCode()==200){
							ServerResponse fn=(ServerResponse)this.toPDF(temp);
							if(fn.getCode()==200){
								this.delMsg(user);
								return ServerResponse.createBySuccessMessage("保存成功");
							}else{
								return fn;
							}
						}else{
							return sm;
						}
						
					}else{
						return ServerResponse.createByErrorMessage("数据库不存在记录");
					}
					
				}else{
					return cf;
				}
				
			}else{
				return ServerResponse.createByErrorMessage("数据格式错误");
			}
		
	}

	public boolean checkInput(Swyreport temp,int i){
		if(i>0||(temp.getRecYear()!=null&&
				   temp.getGroundWater()!=null&&
				   temp.getIndustrySum()!=null&&
			       temp.getRecycleSum()!=null&&
				   temp.getSurfaceWater()!=null&&
				   temp.getTrapWater()!=null&&
				   StringUtils.isNotBlank(temp.getReporter()))){
					return true;
				}else{
					return false;
				}
	}
	
	@Override
	public List<Swyreport> getMsgByAccount(User user) {
		return swyreportMapper.getMsgByAccount(user);
	}

	@Override
	public List<Map<String, String>> getHangyeCode() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Swyreport> getMsgByAccountExcell(Swyreport swyreport) {
		
		/*File file=new File(mainPath+swyreport.getAccount()+"_用水单位基本信息.xlsx");
		 FileInputStream fis;
		try {
			fis = new FileInputStream(file);
			Workbook workbook= WorkbookFactory.create(fis);
			Sheet sheet=workbook.getSheetAt(0);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		return swyreportMapper.getMsgByAccountExcell(swyreport);
	}

	
	
	private Object createFile(Swyreport swyreport){
		return ExcellUtil.copyFile(mainPath,swyreport,"节水量年报");
	}
	
	private Object stuffMsg(List<Swyreport> swyreportLi,User user){
//		ExcellUtil.insertRows(mainPath+swyreport.getAccount()+"_中水.xlsx", 12,30,16);
		File file=new File(mainPath+swyreportLi.get(0).getAccount()+"_节水量年报.xlsx");
		try {
		FileInputStream fis=new FileInputStream(file);
	     Workbook workbook= WorkbookFactory.create(fis);
	     Sheet sheet=workbook.getSheetAt(0);
	   //填表单位名称
	     if(StringUtils.isNotBlank(user.getCompany())){
	    	 String oldValue=ExcellUtil.getExcellString(sheet,0,6);
	    	 oldValue=oldValue.replace("：", "："+user.getCompany());
	    	 ExcellUtil.updateExcel(sheet,0,6,oldValue);
	     }
	   //年份
	     if(swyreportLi.get(0).getRecYear()!=null){
	    	 String oldValue=ExcellUtil.getExcellString(sheet,1,6);
	    	 oldValue=oldValue.replace("20  ", Integer.toString(swyreportLi.get(0).getRecYear()));
	    	 ExcellUtil.updateExcel(sheet,1,6,oldValue);
	     }
	    
	   //报出日期
		 if(StringUtils.isNotBlank(swyreportLi.get(0).getTs())){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,19);
	    	 oldValue=oldValue.replace("20", swyreportLi.get(0).getTs().substring(0, 4));
	    	 oldValue=oldValue.replace("月", swyreportLi.get(0).getTs().substring(5, 7)+"月");
	    	 oldValue=oldValue.replace("日 ", swyreportLi.get(0).getTs().substring(8, 10)+"日");
			 ExcellUtil.updateExcel(sheet,0,19,oldValue);
		 }
	     
	   //统计负责人： 
		 if(StringUtils.isNotBlank(swyreportLi.get(0).getReporter())){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,19);
			 String preValue="";
			 for(int c=0;c<swyreportLi.get(0).getReporter().length();c++){
				 preValue=preValue+" ";
			 }
	    	 oldValue=oldValue.replace("统计负责人： "+preValue, "统计负责人： "+swyreportLi.get(0).getReporter());
			 ExcellUtil.updateExcel(sheet,0,19,oldValue);
		 }
		//填表人
		 if(StringUtils.isNotBlank(swyreportLi.get(0).getOperater())){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,19);
			 String preValue="";
			 for(int c=0;c<swyreportLi.get(0).getOperater().length();c++){
				 preValue=preValue+" ";
			 }
	    	 oldValue=oldValue.replace("填表人："+preValue, "填表人："+swyreportLi.get(0).getOperater());
			 ExcellUtil.updateExcel(sheet,0,19,oldValue);
		 }
		//电话
		 if(StringUtils.isNotBlank(user.getPhone())){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,19);
			 String preValue="";
			 for(int c=0;c<user.getPhone().length();c++){
				 preValue=preValue+" ";
			 }
	    	 oldValue=oldValue.replace("电话："+preValue, "电话："+user.getPhone());
			 ExcellUtil.updateExcel(sheet,0,19,oldValue);
		 }
		
	     
		for(int i=0;i<swyreportLi.size();i++){
			Swyreport tmp=swyreportLi.get(i);
			 
			//年节水总量
			if(tmp.getIndustrySum()!=null){
				ExcellUtil.updateExcel(sheet,2,10+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getIndustrySum()));
			}
			//工业节水总量
			if(tmp.getRecycleSum()!=null){
				ExcellUtil.updateExcel(sheet,3,10+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getRecycleSum()));
			}
			//地表水
			if(tmp.getSurfaceWater()!=null){
			ExcellUtil.updateExcel(sheet,4,10+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getSurfaceWater()));
			}
			//地下水
			if(tmp.getGroundWater()!=null){
			ExcellUtil.updateExcel(sheet,5,10+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getGroundWater()));
			}
			//市政供水
			if(tmp.getTrapWater()!=null){
			ExcellUtil.updateExcel(sheet,6,10+Integer.parseInt(tmp.getPrjType()),Double.toString(tmp.getTrapWater()));
			}
			/*if("合计".equals(tmp.getPrjType())){
				//年节水总量
				if(tmp.getIndustrySum()!=null){
					ExcellUtil.updateExcel(sheet,2,10,Double.toString(tmp.getIndustrySum()));
				}
				//工业节水总量
				if(tmp.getRecycleSum()!=null){
					ExcellUtil.updateExcel(sheet,3,10,Double.toString(tmp.getRecycleSum()));
				}
				//地表水
				if(tmp.getSurfaceWater()!=null){
				ExcellUtil.updateExcel(sheet,4,10,Double.toString(tmp.getSurfaceWater()));
				}
				//地下水
				if(tmp.getGroundWater()!=null){
				ExcellUtil.updateExcel(sheet,5,10,Double.toString(tmp.getGroundWater()));
				}
				//市政供水
				if(tmp.getTrapWater()!=null){
				ExcellUtil.updateExcel(sheet,6,10,Double.toString(tmp.getTrapWater()));
				}
			}else if("技改等措施节水量小计".equals(tmp.getPrjType())){
				//年节水总量
				if(tmp.getIndustrySum()!=null){
					ExcellUtil.updateExcel(sheet,2,11,Double.toString(tmp.getIndustrySum()));
				}
				//工业节水总量
				if(tmp.getRecycleSum()!=null){
					ExcellUtil.updateExcel(sheet,3,11,Double.toString(tmp.getRecycleSum()));
				}
				//地表水
				if(tmp.getSurfaceWater()!=null){
				ExcellUtil.updateExcel(sheet,4,11,Double.toString(tmp.getSurfaceWater()));
				}
				//地下水
				if(tmp.getGroundWater()!=null){
				ExcellUtil.updateExcel(sheet,5,11,Double.toString(tmp.getGroundWater()));
				}
				//市政供水
				if(tmp.getTrapWater()!=null){
				ExcellUtil.updateExcel(sheet,6,11,Double.toString(tmp.getTrapWater()));
				}
			}else if("节水技改项目".equals(tmp.getPrjType())){
				//年节水总量
				if(tmp.getIndustrySum()!=null){
					ExcellUtil.updateExcel(sheet,2,12,Double.toString(tmp.getIndustrySum()));
				}
				//工业节水总量
				if(tmp.getRecycleSum()!=null){
					ExcellUtil.updateExcel(sheet,3,12,Double.toString(tmp.getRecycleSum()));
				}
				//地表水
				if(tmp.getSurfaceWater()!=null){
				ExcellUtil.updateExcel(sheet,4,12,Double.toString(tmp.getSurfaceWater()));
				}
				//地下水
				if(tmp.getGroundWater()!=null){
				ExcellUtil.updateExcel(sheet,5,12,Double.toString(tmp.getGroundWater()));
				}
				//市政供水
				if(tmp.getTrapWater()!=null){
				ExcellUtil.updateExcel(sheet,6,12,Double.toString(tmp.getTrapWater()));
				}
			}else if("推广节水器具".equals(tmp.getPrjType())){
				//年节水总量
				if(tmp.getIndustrySum()!=null){
					ExcellUtil.updateExcel(sheet,2,13,Double.toString(tmp.getIndustrySum()));
				}
				//工业节水总量
				if(tmp.getRecycleSum()!=null){
					ExcellUtil.updateExcel(sheet,3,13,Double.toString(tmp.getRecycleSum()));
				}
				//地表水
				if(tmp.getSurfaceWater()!=null){
				ExcellUtil.updateExcel(sheet,4,13,Double.toString(tmp.getSurfaceWater()));
				}
				//地下水
				if(tmp.getGroundWater()!=null){
				ExcellUtil.updateExcel(sheet,5,13,Double.toString(tmp.getGroundWater()));
				}
				//市政供水
				if(tmp.getTrapWater()!=null){
				ExcellUtil.updateExcel(sheet,6,13,Double.toString(tmp.getTrapWater()));
				}
			}else if("降低自来水管漏失节水量".equals(tmp.getPrjType())){
				//年节水总量
				if(tmp.getIndustrySum()!=null){
					ExcellUtil.updateExcel(sheet,2,14,Double.toString(tmp.getIndustrySum()));
				}
				//工业节水总量
				if(tmp.getRecycleSum()!=null){
					ExcellUtil.updateExcel(sheet,3,14,Double.toString(tmp.getRecycleSum()));
				}
				//地表水
				if(tmp.getSurfaceWater()!=null){
				ExcellUtil.updateExcel(sheet,4,14,Double.toString(tmp.getSurfaceWater()));
				}
				//地下水
				if(tmp.getGroundWater()!=null){
				ExcellUtil.updateExcel(sheet,5,14,Double.toString(tmp.getGroundWater()));
				}
				//市政供水
				if(tmp.getTrapWater()!=null){
				ExcellUtil.updateExcel(sheet,6,14,Double.toString(tmp.getTrapWater()));
				}
			}else if("压缩用水计划等综合管理措施".equals(tmp.getPrjType())){
				//年节水总量
				if(tmp.getIndustrySum()!=null){
					ExcellUtil.updateExcel(sheet,2,15,Double.toString(tmp.getIndustrySum()));
				}
				//工业节水总量
				if(tmp.getRecycleSum()!=null){
					ExcellUtil.updateExcel(sheet,3,15,Double.toString(tmp.getRecycleSum()));
				}
				//地表水
				if(tmp.getSurfaceWater()!=null){
				ExcellUtil.updateExcel(sheet,4,15,Double.toString(tmp.getSurfaceWater()));
				}
				//地下水
				if(tmp.getGroundWater()!=null){
				ExcellUtil.updateExcel(sheet,5,15,Double.toString(tmp.getGroundWater()));
				}
				//市政供水
				if(tmp.getTrapWater()!=null){
				ExcellUtil.updateExcel(sheet,6,15,Double.toString(tmp.getTrapWater()));
				}
			}else if("增加使用再生水及中水小计".equals(tmp.getPrjType())){
				//年节水总量
				if(tmp.getIndustrySum()!=null){
					ExcellUtil.updateExcel(sheet,2,16,Double.toString(tmp.getIndustrySum()));
				}
				//工业节水总量
				if(tmp.getRecycleSum()!=null){
					ExcellUtil.updateExcel(sheet,3,16,Double.toString(tmp.getRecycleSum()));
				}
				//地表水
				if(tmp.getSurfaceWater()!=null){
				ExcellUtil.updateExcel(sheet,4,16,Double.toString(tmp.getSurfaceWater()));
				}
				//地下水
				if(tmp.getGroundWater()!=null){
				ExcellUtil.updateExcel(sheet,5,16,Double.toString(tmp.getGroundWater()));
				}
				//市政供水
				if(tmp.getTrapWater()!=null){
				ExcellUtil.updateExcel(sheet,6,16,Double.toString(tmp.getTrapWater()));
				}
			}else if("新增使用建筑中水".equals(tmp.getPrjType())){
				//年节水总量
				if(tmp.getIndustrySum()!=null){
					ExcellUtil.updateExcel(sheet,2,17,Double.toString(tmp.getIndustrySum()));
				}
				//工业节水总量
				if(tmp.getRecycleSum()!=null){
					ExcellUtil.updateExcel(sheet,3,17,Double.toString(tmp.getRecycleSum()));
				}
				//地表水
				if(tmp.getSurfaceWater()!=null){
				ExcellUtil.updateExcel(sheet,4,17,Double.toString(tmp.getSurfaceWater()));
				}
				//地下水
				if(tmp.getGroundWater()!=null){
				ExcellUtil.updateExcel(sheet,5,17,Double.toString(tmp.getGroundWater()));
				}
				//市政供水
				if(tmp.getTrapWater()!=null){
				ExcellUtil.updateExcel(sheet,6,17,Double.toString(tmp.getTrapWater()));
				}
			}else if("新增使用市政中水".equals(tmp.getPrjType())){
				//年节水总量
				if(tmp.getIndustrySum()!=null){
					ExcellUtil.updateExcel(sheet,2,18,Double.toString(tmp.getIndustrySum()));
				}
				//工业节水总量
				if(tmp.getRecycleSum()!=null){
					ExcellUtil.updateExcel(sheet,3,18,Double.toString(tmp.getRecycleSum()));
				}
				//地表水
				if(tmp.getSurfaceWater()!=null){
				ExcellUtil.updateExcel(sheet,4,18,Double.toString(tmp.getSurfaceWater()));
				}
				//地下水
				if(tmp.getGroundWater()!=null){
				ExcellUtil.updateExcel(sheet,5,18,Double.toString(tmp.getGroundWater()));
				}
				//市政供水
				if(tmp.getTrapWater()!=null){
				ExcellUtil.updateExcel(sheet,6,18,Double.toString(tmp.getTrapWater()));
				}
			}else{
				return ServerResponse.createByErrorMessage("数据结构错误");
			}*/
		}
		fis.close();//关闭文件输入流
		 
	     FileOutputStream fos=new FileOutputStream(file);
	     workbook.write(fos);
	     fos.close();//关闭文件输出流
		 
		 return ServerResponse.createBySuccessMessage("填充数据成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ServerResponse.createBySuccessMessage("修改excell成功");
	}
	
	private Object toPDF(Swyreport swyreport){
		try {
			return ExcellUtil.excel2Pdf(mainPath,swyreport,"节水量年报");
		} catch (Exception e) {
			return ServerResponse.createByErrorMessage(e.getMessage());
		}
	}
	
	private void delMsg(User user){
		swyreportMapper.delMsg(user);
		swyreportMapper.updateVersion(user);
	}
	
	@Override
	public Object checkCommit(User user) {
		List<Swyreport> swyreportLi=this.getMsgByAccount(user);
		if(swyreportLi.size()>0){
			
			for(int i=0;i<swyreportLi.size();i++){
				Swyreport temp=swyreportLi.get(i);
				if( i==0&&
						(temp.getRecYear()==null||
						StringUtils.isBlank(temp.getPrjType())||
						temp.getIndustrySum()==null||
						temp.getRecycleSum()==null||
						temp.getTrapWater()==null||
						temp.getSurfaceWater()==null||
						temp.getGroundWater()==null||
						StringUtils.isBlank(temp.getReporter()))
						){
					return ServerResponse.createByErrorMessage("节水量年报内容尚未填写完成");
				}
			}
			return ServerResponse.createBySuccessMessage("节水量年报内容填写完成");
		}else{
			return ServerResponse.createByErrorMessage("节水量年报内容尚未填写完成");
		}
	}
	@Override
	public int getIfComit(User user) {
		return swyreportMapper.getIfComit(user);
	}

	@Override
	public int updateComit() {
		return swyreportMapper.updateComit();
	}

	@Override
	public Object bulidEmptyFile(String path, Swyreport swyreport, User user) {
		mainPath=path;
		List<Swyreport> temp=new ArrayList<Swyreport>();
		temp.add(swyreport);
		//初始化excell成功
		ServerResponse cf=(ServerResponse)this.createFile(swyreport);
		if(cf.getCode()==200){
			//
			ServerResponse sm=(ServerResponse)this.stuffMsg(temp,user);
			if(sm.getCode()==200){
				ServerResponse fn=(ServerResponse)this.toPDF(swyreport);
					if(fn.getCode()==200){
						return ServerResponse.createBySuccessMessage("保存成功");
					}else{
						return fn;
					}
			}else{
				return sm;
			}
			
			}else{
				return ServerResponse.createByErrorMessage("数据库不存在记录");
			}
	}
}
